/**
 * 所有版权归 广西梧州 陈锦韬 所有
 *
 * @Title: SystemService
 * @Package com.rx.uua.service
 * @Description: 系统管理服务
 * @author: 陈锦韬
 * @date: 2021\7\7 0007
 * @version V1.0
 * @Copyright: 2021 陈锦韬  All rights reserved.
 */
package com.rx.uua.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rx.core.base.RxBaseConstant;
import com.rx.core.base.RxBaseData;
import com.rx.core.base.RxResponse;
import com.rx.core.bean.LoginUserInfo;
import com.rx.core.bean.RxBCryptPasswordEncoder;
import com.rx.core.enm.*;
import com.rx.core.iface.RelationQuery;
import com.rx.core.iface.ReturnInputMode;
import com.rx.core.iface.TreeNode;
import com.rx.core.service.RxBaseAbstractService;
import com.rx.core.service.StandardService;
import com.rx.core.util.EmptyChecker;
import com.rx.core.util.RxContentHolder;
import com.rx.core.util.RxUtil;
import com.rx.uua.dao.UuaRelGroupMapper;
import com.rx.uua.dao.UuaUserInfoMapper;
import com.rx.uua.dto.MenuInfo;
import com.rx.uua.dto.SearchMenu;
import com.rx.uua.enm.MENU_AUTH_TYPE;
import com.rx.uua.enm.RELATION_TYPE;
import com.rx.uua.enm.RESOURCE_TYPE;
import com.rx.uua.vo.*;
import com.rx.uua.vo.relation.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.UnsupportedGrantTypeException;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import java.security.Principal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: Administrator
 * @Description: 系统管理服务
 * @date: 2021\7\7 0007
 */
@Service
@Slf4j
public class SystemService extends RxBaseAbstractService {

    @Autowired
    StandardService standardService;
    @Autowired
    UuaUserInfoMapper uuaUserInfoMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    UuaRelGroupMapper uuaRelGroupMapper;

    @Autowired
    RxUserDetailsService rxUserDetailsService;

    @Autowired @Lazy
    TokenEndpoint tokenEndpoint;

    @Transactional
    public Object changePassword(ChangePasswordVo changePasswordVo){
        UuaUserInfo condition = null;
        UuaUserInfo uuaUserInfo = null;
        try {
            condition = (UuaUserInfo)RxBaseData.create(UuaUserInfo.class, HANDLER_TYPE.SINGLE_DETAIL);
            condition.setBid(changePasswordVo.getBid());
            uuaUserInfo = (UuaUserInfo)standardService.detail(condition);
        } catch (Throwable e) {
            log.error(RX_LOG_MODE.ERROR.getFormat(" 异常不处理{}"),e.getMessage());
        }


        RxUtil.CheckUtil.check(uuaUserInfo, RESULT_CODE.MESSAGE,"用户不存在");

        RxBCryptPasswordEncoder rxBCryptPasswordEncoder = (RxBCryptPasswordEncoder)passwordEncoder;
        // 比较老密码
        boolean yesOld = rxBCryptPasswordEncoder.matches(false,changePasswordVo.getOldPassword(),uuaUserInfo.getPassword());

        RxUtil.CheckUtil.condition(!yesOld, RESULT_CODE.MESSAGE,"旧密码错误");
        // 更新新密码
        String encodePwd = BCrypt.hashpw(rxBCryptPasswordEncoder.decodePassword(false,changePasswordVo.getNewPassword())
                ,BCrypt.gensalt());

        try {
            condition = (UuaUserInfo)RxBaseData.create(UuaUserInfo.class, HANDLER_TYPE.SINGLE_UPDATE);
            condition.setBid(changePasswordVo.getBid());
            if (uuaUserInfo.getLoginCount() < 1 ){
                condition.setLoginCount(1L);
            }
            condition.setPassword(encodePwd);
            standardService.update(condition);
        } catch (Throwable e) {
            log.error(RX_LOG_MODE.ERROR.getFormat(" 异常不处理{}"),e.getMessage());
        }
        return RxResponse.ok();
    }

    public List<UuaRelGroup> getConflictRoleList(List<String> roleBidList,String status){
        if (EmptyChecker.isEmpty(roleBidList)){
            return new ArrayList<>();
        }
        QueryWrapper<UuaRelGroup> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("relation_type", RELATION_TYPE.ROLE_TO_ROLE.getValue());
        queryWrapper.eq("valid", RX_VALID.NORMAL.getCode());
        if (EmptyChecker.notEmpty(status)){
            queryWrapper.eq("status", status);
        }
        queryWrapper.and(wrapper -> wrapper.in("group_bid",roleBidList).or().in("item_bid",roleBidList));
        List<UuaRelGroup> resultList = uuaRelGroupMapper.selectList(queryWrapper);
        if (EmptyChecker.isEmpty(resultList)){
            return new ArrayList<>();
        }
        return resultList;
    }

    private List<LoginUserInfo.RoleInfo> defalutRole() throws InstantiationException, IllegalAccessException {
        UuaRoleInfo condition = (UuaRoleInfo) RxBaseData.create(UuaRoleInfo.class,HANDLER_TYPE.SINGLE_LIST);
        condition.setStatus(RX_STATUS.NORMAL.getCode());
        condition.setRoleCode(RxBaseConstant.ROLE_DEFAULT);
        condition.getHandlerController().onlyDefault();
        List<UuaRoleInfo> list = RxUtil.result(standardService.searchList(condition));
        if(EmptyChecker.isEmpty(list)){
            return new ArrayList<>();
        }

        UuaRoleInfo uuaRoleInfo = (UuaRoleInfo)RxUtil.ListUtil.getFirst(list);
        List<LoginUserInfo.RoleInfo> result = new ArrayList<>();


        LoginUserInfo.RoleInfo roleInfo = new LoginUserInfo.RoleInfo();
        RxUtil.copyProperties(uuaRoleInfo,roleInfo);
        result.add(roleInfo);
        return result;
    }

    /**
     * 默认菜单
     * @return
     */
    private Object defalutMenu() throws InstantiationException, IllegalAccessException {
        // 把首页返回。
        return new ArrayList<>();
    }

    private void changeToken(SearchMenu searchMenu,UuaOrgInfo uuaOrgInfo){
        UsernamePasswordAuthenticationToken principal = new UsernamePasswordAuthenticationToken(User.withUsername("username")
                .password("password")
                .accountExpired(false).authorities("all").build(),null,Collections.emptyList());



        Map<String, String> parameters = new HashMap<>();
        parameters.put("client_id","username");
        parameters.put("client_secret","client_secret");
        parameters.put("grant_type","password");
        parameters.put("password","password");
        parameters.put("username",RxContentHolder.getUserInfo().getUserName()+"@&@"+uuaOrgInfo.getBid());
        parameters.put("code","change_org");
        try {
            ResponseEntity<OAuth2AccessToken> object = tokenEndpoint.postAccessToken(principal,parameters);
            log.info(object.getBody().getValue().toString());
            searchMenu.setTokenMessage(object.getBody());
        } catch (HttpRequestMethodNotSupportedException e) {
            e.printStackTrace();
        }
    }
    /**
     * 获取菜单
     * @param uuaOrgInfo
     * @return
     */
    public Object searchMenu(UuaOrgInfo uuaOrgInfo){
        try {
            SearchMenu searchMenu = new SearchMenu();



            if (RX_USER_TYPE.SYS.getCode().equalsIgnoreCase(RxContentHolder.getUserInfo().getUserType())){
                // 系统用户不能根据登录机构获取角色
                uuaOrgInfo.setBid(RxBaseConstant.ORG_DEFAULT);
            }else {
                RxContentHolder.getCurrentOrg(uuaOrgInfo.getBid());
                changeToken(searchMenu,uuaOrgInfo);
            }

            List<LoginUserInfo.RoleInfo> list = rxUserDetailsService.getRoleList(uuaOrgInfo.getBid());
            if (EmptyChecker.isEmpty(list)){
                list = defalutRole();
                if(EmptyChecker.isEmpty(list)){
                    searchMenu.setRouteList((List)defalutMenu());
                    return searchMenu;
                }
            }else{
                list.addAll(defalutRole());
            }
            RxContentHolder.getUser().setRoleList(list);







            DoubleUuaMenuInfo condition = (DoubleUuaMenuInfo) RxBaseData.create(DoubleUuaMenuInfo.class,UuaRelRoleResource.class,HANDLER_TYPE.DOUBLE_LIST);
            condition.setStatus(RX_STATUS.NORMAL.getCode());

            UuaRelRoleResource relation = (UuaRelRoleResource) condition.getRelation();
            relation.setStatus(RX_STATUS.NORMAL.getCode());
            // 菜单类型
            relation.setResourceType(RESOURCE_TYPE.MENU.getValue());
            // 与第一张表关联的字段是ITEM_BID
            relation.setReturnType(UuaRelRoleResource.ASS_ITEM_BID);
            Map<String,Object> conditionRang = new HashMap<>();
            List<String> roleBidList = list.stream().map(LoginUserInfo.RoleInfo::getBid).collect(Collectors.toList());

            conditionRang.put("inGroupBid",roleBidList);
            relation.setCondition(conditionRang);

            Object object = standardService.innerSearchList(condition);
            if (object instanceof RxResponse){
                return defalutMenu();
            }
            if (EmptyChecker.isEmpty(object)){
                return defalutMenu();
            }
            List<DoubleUuaMenuInfo> resultList = (List<DoubleUuaMenuInfo>) object;
            if (EmptyChecker.isEmpty(resultList)){
                return defalutMenu();
            }
            // 排序
            resultList = dealWhiteBlack(resultList);
            List<TreeNode> treeNodeList = new ArrayList<>();
            for (DoubleUuaMenuInfo doubleUuaMenuInfo : resultList) {
                treeNodeList.add(MenuInfo.create(doubleUuaMenuInfo));
            }
            if (EmptyChecker.isEmpty(treeNodeList)){
                return defalutMenu();
            }
            treeNodeList=RxUtil.ListUtil.listToTree(treeNodeList,RxBaseConstant.ORG_ROOT);

            searchMenu.setRouteList(treeNodeList);
            return searchMenu;

        } catch (IllegalAccessException | InstantiationException e) {
            log.error(RX_LOG_MODE.ERROR.getFormat("查询菜单权限失败"));
        }
        return null;
    }

    private List<UuaMenuInfo> getAllMenuInfo(){
        try {
            List<LoginUserInfo.RoleInfo> list = RxContentHolder.getContext().getUserInfo().getRoleList();
            if (EmptyChecker.isEmpty(list)){
                return Collections.emptyList();
            }

            UuaMenuInfo condition = (UuaMenuInfo) RxBaseData.create(UuaMenuInfo.class,HANDLER_TYPE.SINGLE_LIST);
            condition.setStatus(RX_STATUS.NORMAL.getCode());

            Object object = standardService.searchList(condition);
            if (object instanceof RxResponse){
                return Collections.emptyList();
            }
            if (EmptyChecker.isEmpty(object)){
                return Collections.emptyList();
            }
            List<UuaMenuInfo> resultList = (List<UuaMenuInfo>) object;
            if (EmptyChecker.isEmpty(resultList)){
                return Collections.emptyList();
            }
            return resultList;

        } catch (IllegalAccessException | InstantiationException e) {
            log.error(RX_LOG_MODE.ERROR.getFormat("查询菜单权限失败"));
        }
        return Collections.emptyList();
    }
    private List<DoubleUuaMenuInfo> dealWhiteBlack(List<DoubleUuaMenuInfo> resultList){
        // 黑名单/白名单处理
        Map<String,List<DoubleUuaMenuInfo>> groupMap = resultList.stream()
                .collect(Collectors.groupingBy(e->((UuaRelRoleResource)e.obtainRelation()).getType()));

        List<DoubleUuaMenuInfo> menuInfoWhiteList = groupMap.get(MENU_AUTH_TYPE.DEFAULT.getValue());
        List<DoubleUuaMenuInfo> menuInfoBlackList = groupMap.get(MENU_AUTH_TYPE.BLACK.getValue());
        if (EmptyChecker.isEmpty(menuInfoWhiteList)){
            // 无白名单。按黑名单排除查询
            menuInfoBlackList = distinct(menuInfoBlackList);
            List<UuaMenuInfo> allList = getAllMenuInfo();
            return removeBlackFromAll(allList,menuInfoBlackList);
        }
        menuInfoWhiteList = distinct(menuInfoWhiteList);
        if (EmptyChecker.isEmpty(menuInfoBlackList)){
            return menuInfoWhiteList;
        }
        menuInfoBlackList = distinct(menuInfoBlackList);
        return removeBlack(menuInfoWhiteList,menuInfoBlackList);
    }
    private List<DoubleUuaMenuInfo> distinct(List<DoubleUuaMenuInfo> menuInfoWhiteList){
        List<DoubleUuaMenuInfo> result = new ArrayList<>();
        for (DoubleUuaMenuInfo doubleUuaMenuInfo : menuInfoWhiteList) {
            boolean repeat = false;
            for (DoubleUuaMenuInfo uuaMenuInfo : result) {
                if (uuaMenuInfo.getBid().equalsIgnoreCase(doubleUuaMenuInfo.getBid())){
                    repeat = true;
                    break;
                }
            }
            if (!repeat){
                result.add(doubleUuaMenuInfo);
            }
        }
        return result;
    }
    private List<DoubleUuaMenuInfo> removeBlack(List<DoubleUuaMenuInfo> menuInfoWhiteList,List<DoubleUuaMenuInfo> menuInfoBlackList){
        Iterator<DoubleUuaMenuInfo> iterator = menuInfoWhiteList.iterator();
        while (iterator.hasNext()){
            DoubleUuaMenuInfo uuaMenuInfoWhite = iterator.next();
            for (DoubleUuaMenuInfo doubleUuaMenuInfo : menuInfoBlackList) {
                if (doubleUuaMenuInfo.getBid().equalsIgnoreCase(uuaMenuInfoWhite.getBid())){
                    iterator.remove();
                    break;
                }
            }
        }
        return menuInfoWhiteList;
    }
    private List<DoubleUuaMenuInfo> removeBlackFromAll(List<UuaMenuInfo> menuInfoList,List<DoubleUuaMenuInfo> menuInfoBlackList){
        if (EmptyChecker.isEmpty(menuInfoList) || EmptyChecker.isEmpty(menuInfoBlackList)){
            return Collections.emptyList();
        }
        List<DoubleUuaMenuInfo> resultList = new ArrayList<>();
        Iterator<UuaMenuInfo> iterator = menuInfoList.iterator();
        while (iterator.hasNext()){
            UuaMenuInfo uuaMenuInfoWhite = iterator.next();
            boolean remove = false;
            for (DoubleUuaMenuInfo doubleUuaMenuInfo : menuInfoBlackList) {
                if (doubleUuaMenuInfo.getBid().equalsIgnoreCase(uuaMenuInfoWhite.getBid())){
                    iterator.remove();
                    remove = true;
                    break;
                }
            }

            if (!remove){
                DoubleUuaMenuInfo doubleUuaMenuInfo = new DoubleUuaMenuInfo();
                RxUtil.copyProperties(uuaMenuInfoWhite,doubleUuaMenuInfo);
                resultList.add(doubleUuaMenuInfo);
            }
        }
        return resultList;
    }
    /**
     *  获取用户管理的机构
      */
    private List<DoubleUuaOrgInfo> getOrgList(List<String> relationTyleList,String bid) throws InstantiationException, IllegalAccessException {
        DoubleUuaOrgInfo conditionOrg = (DoubleUuaOrgInfo)RxBaseData.create(DoubleUuaOrgInfo.class,UuaRelUserOrg.class,HANDLER_TYPE.DOUBLE_LIST);
        UuaRelUserOrg uuaRelUserOrg = new UuaRelUserOrg();
        uuaRelUserOrg.setItemBid(bid);

        if(EmptyChecker.isEmpty(relationTyleList)){
            uuaRelUserOrg.setRelationType(RELATION_TYPE.USER_TO_ORG.getValue());
        }else {
            if (relationTyleList.size() == 1){
                uuaRelUserOrg.setRelationType((String)RxUtil.ListUtil.getFirst(relationTyleList));
            }else {
                Map<String,Object> map = new HashMap<>();
                map.put("inRelationType",relationTyleList);
                uuaRelUserOrg.setCondition(map);
            }

        }
        uuaRelUserOrg.setStatus(RX_STATUS.NORMAL.getCode());
//        LoginUserInfo.OrgInfo orgInfo = RxContentHolder.getCurrentOrg();
//        if(EmptyChecker.notEmpty(orgInfo)){
//            conditionOrg.setRootCode(orgInfo.getOrgCode());
//        }

        conditionOrg.setRelation(uuaRelUserOrg);
        Object object = standardService.innerSearchList(conditionOrg);
        return RxUtil.result(object);
    }
    public String getGroupBidFromFront(RxBaseData rxBaseData){
        Map<String,Object> map = rxBaseData.getCondition();
        String groupBid = null;
        if(map != null){
            groupBid = (String)map.get("groupBid");
            if(EmptyChecker.notEmpty(groupBid)){
                map.remove("groupBid");
            }
        }
        return groupBid;
    }
    public List<DoubleUuaRelUserOrg> getOrgListForAdmin(String groupBid,String bid) throws InstantiationException, IllegalAccessException {
        DoubleUuaRelUserOrg conditionOrg = (DoubleUuaRelUserOrg)RxBaseData.create(DoubleUuaRelUserOrg.class,UuaRelUserOrg.class,HANDLER_TYPE.DOUBLE_LIST);

        UuaRelUserOrg uuaRelUserOrg = new UuaRelUserOrg();
        uuaRelUserOrg.setRelationType(RELATION_TYPE.USER_ADMIN.getValue());
        uuaRelUserOrg.setStatus(RX_STATUS.NORMAL.getCode());

        conditionOrg.setRelation(uuaRelUserOrg);
        conditionOrg.setStatus(RX_STATUS.NORMAL.getCode());
        conditionOrg.setItemBid(bid);
        conditionOrg.setGroupBid(groupBid);
        conditionOrg.setRelationType(RELATION_TYPE.USER_TO_ORG.getValue());
        conditionOrg.setReturnType(Integer.valueOf(3));
        Object object = standardService.innerSearchList(conditionOrg);
        return RxUtil.result(object);
    }
    private UuaRelUserOrg createRelUserOrg(String groupBid,String bid){
        UuaRelUserOrg uuaRelUserOrg = new UuaRelUserOrg();
        uuaRelUserOrg.setRelationType(RELATION_TYPE.USER_TO_ORG.getValue());
        uuaRelUserOrg.setStatus(RX_STATUS.NORMAL.getCode());
        uuaRelUserOrg.setReturnType(UuaRelUserOrg.ASS_ROLE_BID);

        uuaRelUserOrg.setItemBid(bid);
        uuaRelUserOrg.setGroupBid(groupBid);
        return uuaRelUserOrg;
    }
    public List<DoubleUuaRoleInfo> getRoleListForAdmin(String groupBid,String bid) throws InstantiationException, IllegalAccessException {
        DoubleUuaRoleInfo conditionRole = (DoubleUuaRoleInfo)RxBaseData.create(DoubleUuaRoleInfo.class,DoubleUuaRelUserRole.class,UuaRelUserOrg.class,HANDLER_TYPE.THREE_LIST);
        conditionRole.setStatus(RX_STATUS.NORMAL.getCode());

        DoubleUuaRelUserRole uuaRelUserRole = new DoubleUuaRelUserRole();
        uuaRelUserRole.setRelationType(RELATION_TYPE.USER_ADMIN.getValue());
        uuaRelUserRole.setStatus(RX_STATUS.NORMAL.getCode());
        conditionRole.setRelation(uuaRelUserRole);
        uuaRelUserRole.setReturnType(DoubleUuaRelUserRole.ASS_GROUP_BID);

        UuaRelUserOrg uuaRelUserOrg = createRelUserOrg(groupBid,bid);
        uuaRelUserRole.setRelation(uuaRelUserOrg);

        Object object = standardService.threeInnerSearchList(conditionRole);
        return RxUtil.result(object);
    }
    public List<DoubleUuaPostInfo> getPostListForAdmin(String groupBid,String bid) throws InstantiationException, IllegalAccessException {
        DoubleUuaPostInfo conditionPost = (DoubleUuaPostInfo)RxBaseData.create(DoubleUuaPostInfo.class,DoubleUuaRelUserPost.class,UuaRelUserOrg.class,HANDLER_TYPE.THREE_LIST);
        conditionPost.setStatus(RX_STATUS.NORMAL.getCode());

        DoubleUuaRelUserPost uuaRelUserRole = new DoubleUuaRelUserPost();
        uuaRelUserRole.setRelationType(RELATION_TYPE.USER_ADMIN.getValue());
        uuaRelUserRole.setStatus(RX_STATUS.NORMAL.getCode());
        conditionPost.setRelation(uuaRelUserRole);
        uuaRelUserRole.setReturnType(DoubleUuaRelUserRole.ASS_GROUP_BID);

        UuaRelUserOrg uuaRelUserOrg = createRelUserOrg(groupBid,bid);
        uuaRelUserRole.setRelation(uuaRelUserOrg);

        Object object = standardService.threeInnerSearchList(conditionPost);
        return RxUtil.result(object);
    }
    public List<String> getOrgListFromDb(List<String> relationTypeList,String bid, ReturnInputMode returnInputMode){
        try {
            List<DoubleUuaOrgInfo> uuaOrgInfoList = getOrgList(relationTypeList,bid);
            if(EmptyChecker.isEmpty(uuaOrgInfoList)){
                return new ArrayList<>();
            }
            // 获取所有下级。
            List<String> rootList = uuaOrgInfoList.stream().filter(e->!RxBaseConstant.ORG_ROOT.equalsIgnoreCase(e.getRootCode())).map(DoubleUuaOrgInfo::getRootCode).collect(Collectors.toList());
            List<DoubleUuaOrgInfo> rootPList = uuaOrgInfoList.stream().filter(e->RxBaseConstant.ORG_ROOT.equalsIgnoreCase(e.getRootCode())).collect(Collectors.toList());



            UuaOrgInfo rootCondition = (UuaOrgInfo)RxBaseData.create(UuaOrgInfo.class,HANDLER_TYPE.SINGLE_LIST);


            LoginUserInfo.OrgInfo orgInfo = RxContentHolder.getCurrentOrg();
            if(EmptyChecker.isEmpty(orgInfo)){
                for (DoubleUuaOrgInfo doubleUuaOrgInfo : rootPList) {
                    rootList.add(doubleUuaOrgInfo.getOrgCode());
                }
                Map<String,Object> mapForRoot = new HashMap<>();
                mapForRoot.put("inRootCode",rootList.stream().distinct().collect(Collectors.toList()));
                rootCondition.setCondition(mapForRoot);
            }else {
                // 当前机构。
                rootCondition.setRootCode(orgInfo.getOrgCode());
                Iterator<DoubleUuaOrgInfo> iterator = rootPList.iterator();
                while (iterator.hasNext()){
                    DoubleUuaOrgInfo doubleUuaOrgInfo = iterator.next();
                    if(!doubleUuaOrgInfo.getOrgCode().equalsIgnoreCase(orgInfo.getOrgCode())){
                        iterator.remove();
                    }
                }
            }

            rootCondition.setStatus(RX_STATUS.NORMAL.getCode());
            // 不运行处理器。
            rootCondition.getHandlerController().onlyDefault();
            //rootCondition.
            Object object = standardService.searchList(rootCondition);
            List<UuaOrgInfo> uuaOrgInfos = RxUtil.result(object);
            if(EmptyChecker.isEmpty(uuaOrgInfos) && EmptyChecker.isEmpty(rootPList)){
                return uuaOrgInfoList.stream().map((e)->(String)returnInputMode.handle(e)).collect(Collectors.toList());
            }
            uuaOrgInfos.addAll(rootPList);
            // 组成树形
            List<UuaOrgInfo> treeList = RxUtil.ListUtil.listToTree((List)uuaOrgInfos,null);
            List<String> listFromTree = new ArrayList<>();
            for (DoubleUuaOrgInfo doubleUuaOrgInfo : uuaOrgInfoList) {
                for (UuaOrgInfo uuaOrgInfo : treeList) {
                    if(uuaOrgInfo.getRootCode().equalsIgnoreCase(doubleUuaOrgInfo.getRootCode())){
                        if(EmptyChecker.notEmpty(orgInfo)){
                            if(RxBaseConstant.ORG_ROOT.equalsIgnoreCase(doubleUuaOrgInfo.getRootCode())&&
                                    !orgInfo.getOrgCode().equalsIgnoreCase(doubleUuaOrgInfo.getOrgCode())){
                                continue;
                            }
                        }
                        List<UuaOrgInfo> list =  RxUtil.ListUtil.treeToChildList(uuaOrgInfo,doubleUuaOrgInfo);
                        if(EmptyChecker.notEmpty(list)){
                            listFromTree.addAll(list.stream().map((e)->(String)returnInputMode.handle(e)).collect(Collectors.toList()));
                        }
                        listFromTree.add((String)returnInputMode.handle(doubleUuaOrgInfo));
                    }
                }
            }

            return  listFromTree.stream().distinct().collect(Collectors.toList());
        } catch (IllegalAccessException e) {

        } catch (InstantiationException e) {

        }
        return new ArrayList<>();
    }
    public List<String> getOrgListFromDb(String bid, ReturnInputMode returnInputMode){
        return getOrgListFromDb(null,bid,returnInputMode);
    }
    public Object selectUser(DoubleUuaUserInfo doubleUuaUserInfo,Class cls,SelectUser selectUser){
        doubleUuaUserInfo.setRelation(JSON.parseObject(JSON.toJSONString(doubleUuaUserInfo.getRelation()),cls));
        try {
            DoubleUuaUserInfo condition =(DoubleUuaUserInfo)  RxBaseData.create(DoubleUuaUserInfo.class,cls,HANDLER_TYPE.DOUBLE_LEFT_PAGE);
            RxUtil.copyProperties(doubleUuaUserInfo,condition);
            Integer count = null;
            Integer current = null;
            if (!RxContentHolder.systemUser()){
                LoginUserInfo.UserInfo userInfo = RxContentHolder.getUserInfo();
                List<String> bidList = getOrgListFromDb(userInfo.getBid(),(e)->{
                    return ((UuaOrgInfo)e).getBid();
                });


                String groupBid = getGroupBidFromFront(doubleUuaUserInfo);
                List<DoubleUuaRelUserOrg> adminOrgList = getOrgListForAdmin(groupBid,userInfo.getBid());
                bidList.addAll(adminOrgList.stream().map(e->{
                    return ((UuaRelUserOrg)e.getRelation()).getGroupBid();
                }).collect(Collectors.toList()));

                current = doubleUuaUserInfo.getPageNum();
                doubleUuaUserInfo.setPageNum(doubleUuaUserInfo.getPageNum() - 1);
                count = selectUser.count(doubleUuaUserInfo,bidList.stream().distinct().collect(Collectors.toList()));
                if(count > 0){
                    List<UuaUserInfo> list = selectUser.userList(doubleUuaUserInfo,bidList.stream().distinct().collect(Collectors.toList()));
                    Map<String,Object> map = doubleUuaUserInfo.getCondition();
                    if(map == null){
                        map = new HashMap<>();
                        condition.setCondition(map);
                    }
                    map.put("inId",list.stream().map(UuaUserInfo::getId).collect(Collectors.toList()));
                }

                doubleUuaUserInfo.setPageNum(1);

                if(count == 0){
                    IPage page = new Page();
                    page.setTotal(count);
                    page.setCurrent(current);
                    if (page.getSize() > 0){
                        page.setPages(count/page.getSize() + (count%page.getSize() > 0? 1: 0));
                    }
                    return page;
                }
            }else {
                Map<String,Object> map = doubleUuaUserInfo.getCondition();
                if(map != null){
                    map.remove("groupBid");
                }
            }

            Object oResult =  standardService.leftSearchPage(condition);
            if (oResult instanceof IPage && count != null){
                IPage page = (IPage)oResult;
                page.setTotal(count);
                page.setCurrent(current);
                if (page.getSize() > 0){
                    page.setPages(count/page.getSize() + (count%page.getSize() > 0? 1: 0));
                }
            }
            return oResult;
        } catch (IllegalAccessException | InstantiationException e) {
            RxUtil.CheckUtil.throwOut(RESULT_CODE.MESSAGE,"[校验错误]:创建查询失败！");
        }

        return null;
    }
    public Object selectUser(DoubleUuaUserInfo doubleUuaUserInfo){
        return selectUser(doubleUuaUserInfo, UuaRelUserOrg.class, new SelectUser() {
            @Override
            public Integer count(DoubleUuaUserInfo doubleUuaUserInfo, List<String> bidList) {
                return uuaUserInfoMapper.countUser(doubleUuaUserInfo,bidList);
            }

            @Override
            public List<UuaUserInfo> userList(DoubleUuaUserInfo doubleUuaUserInfo, List<String> bidList) {
                return uuaUserInfoMapper.searchUserList(doubleUuaUserInfo,bidList);
            }
        });

    }
    public Object selectUserRole(DoubleUuaUserInfo doubleUuaUserInfo){

        return selectUser(doubleUuaUserInfo, UuaRelUserRole.class, new SelectUser() {
            @Override
            public Integer count(DoubleUuaUserInfo doubleUuaUserInfo, List<String> bidList) {
                return uuaUserInfoMapper.countUser(doubleUuaUserInfo,bidList);
            }

            @Override
            public List<UuaUserInfo> userList(DoubleUuaUserInfo doubleUuaUserInfo, List<String> bidList) {
                return uuaUserInfoMapper.searchUserList(doubleUuaUserInfo,bidList);
            }
        });
    }
    public Object selectUserPost(DoubleUuaUserInfo doubleUuaUserInfo){
        return selectUser(doubleUuaUserInfo, UuaRelUserPost.class, new SelectUser() {
            @Override
            public Integer count(DoubleUuaUserInfo doubleUuaUserInfo, List<String> bidList) {
                return uuaUserInfoMapper.countUser(doubleUuaUserInfo,bidList);
            }

            @Override
            public List<UuaUserInfo> userList(DoubleUuaUserInfo doubleUuaUserInfo, List<String> bidList) {
                return uuaUserInfoMapper.searchUserList(doubleUuaUserInfo,bidList);
            }
        });
    }

    public Object orgUserCount(List<String> bidList){
        Integer count = uuaUserInfoMapper.countUser(new DoubleUuaUserInfo(),bidList);
        return count;
    }

}
